﻿var SITE_URL = 'http://cms.denhongphuc.vn';

/***************************************
= (document.ready)
-------------------------------------- */
$(function () {
    // Show menu when a list item is clicked
    highlights();

    // Popup Quiz
    $("#popup-quiz-close").click(function () {
        disablePopupQuiz();
    });

    $("#bg-popup-quiz").click(function () {
        disablePopupQuiz();
    });
});

function uploadHtml(productId) {
    $('#popup_container').css('display', 'block');

    $('#popup_title').empty();
    $('#popup_message').empty();

    $('#popup_title').append("Tải dữ liệu lên máy chủ");

    $('#popup_message').load('/Upload.aspx?pId=' + productId);
    $('#popup_message').css({ 'overflow-y': 'auto', 'height': '300px' });    
}

function uploadHtml(productId, typeId) {
    $('#popup_container').css('display', 'block');

    $('#popup_title').empty();
    $('#popup_message').empty();

    $('#popup_title').append("Tải dữ liệu lên máy chủ");

    $('#popup_message').load('/Upload.aspx?pId=' + productId + '&tId=' + typeId);
    $('#popup_message').css({ 'overflow-y': 'auto', 'height': '300px' });    
}

//**************************************************************************************************************************************************************//
// COMMON
//**************************************************************************************************************************************************************//

var popupStatus = 0;

function showPopupQuiz() {
    if (popupStatus == 0) {
        $('#bg-popup-quiz').css({ 'opacity': '0.6' });
        $('#bg-popup-quiz').fadeIn('slow');
        $('#popup-quiz').fadeIn('slow');
        popupStatus = 1;

        var wWidth = document.documentElement.clientWidth;
        var wHeight = document.documentElement.clientHeight;

        var popupWidth = $('#popup-quiz').width();
        var popupHeight = $('#popup-quiz').height();

        $('#popup-quiz').css({ 'position': 'fixed', 'top': wHeight / 2 - popupHeight / 2, 'left': wWidth / 2 - popupWidth / 2 });

        $('#bg-popup-quiz').css({ 'height': wHeight }); // only need force for IE6
    }
}

function disablePopupQuiz() {
    $('#bg-popup-quiz').fadeOut('slow');
    $('#popup-quiz').fadeOut('slow');
    popupStatus = 0;
}

// Press Escape Event!
$(document).keypress(function (e) {
    if (e.keyCode == 27 && popupStatus == 1) {
        disablePopupQuiz();
    }
    if (e.keyCode == 27) {
        closePreview();
    }
});


/***************************************
= String Format
-------------------------------------- */
//#region
String.format = function (text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
    }
    return text;
};
//#endregion

function LoadImage(obj, url) {
    obj.src = url;
    obj.onerror = null;
}

/***************************************
= Tiny MCE
-------------------------------------- */
function getMCE() {
    var content = tinyMCE.get('elm1').getContent();
    //console.log('getMCE: ' + content);    
    if (content.length > 0)
        $('#txtBody').val(content);
}

function setMCE(content) {
    console.log('setMCE: ' + content);
    tinyMCE.execCommand('mceInsertContent', false, content);
    //tinyMCE.execCommand('mceInsertContent', false, img);
}

/***************************************
= File Manager Functions
-------------------------------------- */
function openFileManager(type) {    
    var adminUserId = Base64.decode(AdminUserId);
    if (adminUserId > 0) {
        var urlFolder = String.format("files/{0}/{1}", adminUserId, (new Date().getFullYear()));
        viewDirectories(type, urlFolder, true);
        showPopupQuiz();
    }                    
}

/***************************************
= IZ File Manager Functions
-------------------------------------- */
//#region
function openIZFileManager(type) {
    var w = window.open('/Controls/IZFileManager.aspx?type=' + type, 'File Manager', 'status = 1, height = 470, width = 810');
    w.focus();
    return false;
}
//#endregion

//#region  
// Callback Function Of IZFileManager
function setTargetField(value, type) {

    switch (type) {
        case "article":
            $("#txtImage").val(value);
            break;
        case "zodiac":
            $("#txtImageDescription").val(value);
            break;
        case "data":
            $("#txtFilePath").val(value);
            break;
        case "multiple":
            // set list src image to textbox
            $('#txtImageList').val(value);
            $.jGrowl('Ảnh quảng cáo đã được chọn.<br/> Vui lòng nhấn nút "Lưu lại" để cập nhật danh sách', { life: 5000 });               
            break;
        case "slideshow":
            // set list src image to textbox
            $('#txtSlideShowList').val(value);
            $.jGrowl('Ảnh slideshow đã được chọn.<br/> Vui lòng nhấn nút "Lưu lại" để cập nhật danh sách', { life: 5000 });
            break;                                
    }
    window.focus();
}
//#endregion

//**************************************************************************************************************************************************************//

/***************************************
= Get All Rows Have Checked
-------------------------------------- */
//#region 
function selectAllRows(spanChk) {    
    var oItem = spanChk.children;
    var theBox = (spanChk.type == "checkbox") ?
            spanChk : spanChk.children.item[0];
    xState = theBox.checked;
    //elm = theBox.form.elements;
    elm = $("#grdList :checkbox");

    for (i = 0; i < elm.length; i++)
        if (elm[i].type == "checkbox" &&
                  elm[i].id != theBox.id) {
            if (elm[i].checked == xState)
                elm[i].click();
        }
}
//#endregion

/***************************************
= Active Tab
-------------------------------------- */
//#region
function activeTab(tabName) {    
    switch (tabName) {
        case "IsPublished":
            $("#tab8").addClass('activeTab');        
            break;
        case "IsWaitingForPublish":
            $("#tab2").addClass('activeTab');
            break;
        case "IsDraft":
            $("#tab1").addClass('activeTab');
            break;
        case "IsReturned":
            $("#tab4").addClass('activeTab');
            break;
        case "IsRemoved":
            $("#tab16").addClass('activeTab');
            break;
    }
}
//#endregion

/***************************************
= Active Left Navigator
-------------------------------------- */
//#region    
function activeLeftNav(menuId) {    
    if (typeof(menuId) == 'undefined') {
        return;
    }

    if (menuId == 21) {
        $('.pacman').find('a:first').addClass('active'); // Fix menu Hehe Horo
    }

    if (menuId == 5) {
        $('.pacman').find('a:first').addClass('active'); // Fix menu Hehe Horo
    }

    if (menuId == 37) {
        $('.airplane').find('a:first').addClass('active'); // Fix menu Vip Quiz
    }

    if (menuId == 39) {
        $('.star').find('a:first').addClass('active'); // Fix menu Top Quizzer
    }
    
    if (menuId == 41) {
        $('.userComment').find('a:first').addClass('active'); // Fix menu Top Quizzer
    }

    if (menuId == 42) {
        $('.stats').find('a:first').addClass('active'); // Fix menu Thống kê
    }

    var li = $('ul.sub li a.sm' + menuId).parents('li');
    //console.log(li);
    
    var a = $(li).find('a:first');

    $(a).addClass('active');
    
    $('.active').collapsible({
        defaultOpen: 'current',
        cookieName: 'nav',
        speed: 300
    });

    $('.exp').collapsible({
        defaultOpen: 'current',
        cookieName: 'navAct',
        cssOpen: 'active',
        cssClose: 'inactive',
        speed: 300
    });
    
    var sub = $(li).find('.sub:first');
    $(sub).removeAttr('style').show();
}
//#endregion

// Delegare Tooltip
//#region
function delegateTooltip() {
    $('.topDir').tipsy({ fade: true, gravity: 's' });
}
//#endregion

//**************************************************************************************************************************************************************//
// SMALL SIZE
//**************************************************************************************************************************************************************//

/***************************************
= Create Small Size
-------------------------------------- */
//#region
function createSmallSize(title, imagePath, result) {            
    var html = '';
    html += '<div class="smallsize-item">';
    html += '<div class="mt10">';
    html += '<a class="btn14 mr17 floatright topDir" onclick="removeSmallSize(this);" title="Xóa đáp án"><img src="/images/icons/dark/close.png" alt="" /></a>';
    html += '</div>';
    html += '<div class="fix"></div>';

    html += '<div class="rowElem nobg">';
    html += '<label>Tiêu đề</label>';
    html += '<div class="formRight"><input type="text" class="validate[required] sTitle" value="' + title + '"/></div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<div class="rowElem">';
    html += '<label>Chọn ảnh</label>';
    html += '<div class="formRight">';
    html += String.format('<input type="text" style="width: 560px" class="validate[required] sImage floatleft" onmousemove="quickViewImage(\'{0}\', 200, 181);" onmouseout="closePreview();" value="{0}" />', imagePath);
    html += '<a class="btn14 floatleft ml5 topDir" title="Di chuột vào textbox để xem ảnh."><img alt="" src="/images/icons/dark/arrowLeft.png"></a>';
    html += '<span style="line-height: 28px;">&nbsp;(125 x 113)</span>';
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '</div>';            

    html += '<div class="rowElem">';
    html += '<label>Lời chiêm tinh</label>';
    html += '<div class="formRight"><textarea name="textarea" class="validate[required] sResult" cols="" rows="5">' + result + '</textarea></div>';
    html += '<div class="fix"></div>';
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';    

    return html;    
}
//#endregion

/***************************************
= Remove Small Size
-------------------------------------- */
//#region
function removeSmallSize(obj) {   
    $(obj).parents('.smallsize-item').fadeOut('slow', function () {
        $(this).remove();
    });                            
}
//#endregion

/***************************************
= Get Data Small Size
-------------------------------------- */
//#region
function getDataSmallSize() {
    var imageList = '';
    $('.smallsize-item').each(function () {
        imageList += $(this).find('.sImage').val() + '►';
    });
    // set list image to textbox
    $('#txtImageList').val(imageList);
    
    var contentList = '';
    $('.smallsize-item').each(function () {
        contentList += $(this).find('.sTitle').val() + '♥' + $(this).find('.sResult').val() + '►';
    });
    // set list title, result to textbox
    $('#txtContentList').val(contentList);
}
//#endregion

/***************************************
= Bind Data Small Size
-------------------------------------- */
//#region
function binDataSmallSize(quizzyShopId) {
    var lstSmallSize = '';
    $.getJSON("/Handlers/QuizHandler.ashx", { 'command': 'bindsmallsizebyquizzyshop', 'id': quizzyShopId }, function (result) {
        for (var i = 0; i < result.length; i++) {
            lstSmallSize += createSmallSize(result[i].Title, result[i].Image, result[i].Result);
        }
        $('.smallsize').html(lstSmallSize);
    });
}
//#endregion
//**************************************************************************************************************************************************************//
// HighLights (Right Context Menu)
//**************************************************************************************************************************************************************//

//#region
function highlights() {    
    $("#grdList tr td").contextMenu({
        menu: 'myMenu'
    }, function (action, el, pos) {
        console.log('Action: ' + action + " - Id: " + $(el).parents('tr:first').attr("id"));

        var container = $(el).parents('tr:first');

        switch (action) {
            case "homepage":
                container.find('td:eq(2) img').attr({ 'src': '/images/icons/color/pin.png', 'title': 'Nổi bật trang chủ' }).addClass('btn14');
                break;
            case "category":
                container.find('td:eq(2) img').attr({ 'src': '/images/icons/color/paper-clip.png', 'title': 'Nổi bật mục' }).addClass('btn14');
                break;
            case "remove":
                container.find('td:eq(2) img').attr({ 'src': '', 'title': '' }).removeClass('btn14');
                break;
        }

        var splitValue = container.attr("id").split('-');

        if (parseInt(splitValue[0]) > 0 && parseInt(splitValue[1]) > 0 && splitValue[1].length > 0) {
            console.log(splitValue[0] + '-' + splitValue[1] + '-' + splitValue[2]);            

            $.post('/Handlers/QuizHandler.ashx', { 'command': 'highlighthomepagecategpry', 'adminUserId': splitValue[0], 'action': action, 'id': splitValue[1], 'table': splitValue[2] }, function () {
                switch (action) {
                    case "homepage":
                        $.jGrowl('Thiết lập nổi bật trang chủ thành công', { header: 'Thông báo' });
                        break;
                    case "category":
                        $.jGrowl('Thiết lập nổi bật chuyên mục thành công', { header: 'Thông báo' });
                        break;
                    case "remove":
                        $.jGrowl('Xóa thiết lập thành công', { header: 'Thông báo' });
                        break;
                }
            });
        }

        $('.topDir').tipsy({ fade: true, gravity: 's' });
    });
}

//#endregion

//**************************************************************************************************************************************************************//
// BIG SIZE
//**************************************************************************************************************************************************************//

/***************************************
= Show Big Size Result
-------------------------------------- */
//#region
function showBigSizeResult() {
    var max = 0;
    $('.bigsize-item .answerList').each(function () {
        var count = $(this).find('.rowElem').length;
        if (count > max)
            max = count;
    });

    if (max > 0) {        
        var bigSizeResult = '';
        bigSizeResult += '<div class="rowElem">';
        bigSizeResult += '<label>Lời chiêm tinh</label>';
        bigSizeResult += '<div class="formRight">';            
        bigSizeResult += '<textarea name="textarea" class="bResult" cols="" rows="4" style="width: 630px"></textarea>';
        bigSizeResult += '<div class="floatright"><a onclick="removeBigSizeResult(this);" title="Xóa đáp án" class="btn14 mb5 topDir"><img alt="" src="/images/icons/dark/close.png"></a></div>';            
        bigSizeResult += '</div>';
        bigSizeResult += '<div class="fix"></div>';
        bigSizeResult += '</div>';

        var currentCount = $('.bigsize-result .rowElem').length;

        var html = '';
        for (var i = 0; i < max - currentCount; i++) {
            html += bigSizeResult;
        }
        
        $('.bigsize-result').append(html);
        $('#bigSize-result-container').show();
    }
}
//#endregion

/***************************************
= Remove Big Size Result
-------------------------------------- */
//#region
function removeBigSizeResult(obj) {
    $(obj).parents('.rowElem:first').fadeOut('slow', function () {
        $(this).remove();
    });
}
//#endregion

/***************************************
= Get Data Big Size
-------------------------------------- */
//#region
function getDataBigSize() {
    // set list big size result to textbox
    var bigSizeResult = '';
    $('.bigsize-result .bResult').each(function () {
        bigSizeResult += $(this).val() +'►';
    });
    if (bigSizeResult.length > 0) {
        $('#txtBigSizeResultList').val(bigSizeResult);
    }
        
    var questionList = '';
    $('.bigsize-item').each(function() {
        questionList += $(this).find('.bQuestion').val() + '►';
    });
    // set list question to textbox
    $('#txtQuestionList').val(questionList);

    var answerList = '';
    $('.bigsize-item').each(function () {
        $(this).find('.rowElem').each(function () {
            if ($(this).find('.bAnswer').val() != undefined) 
                answerList += $(this).find('.bAnswer').val() + '♥';            
        });
        answerList += '►';
    });
    // set list answer to textbox
    $('#txtAnswerList').val(answerList);
}
//#endregion

/***************************************
= Bind Data Big Size
-------------------------------------- */
//#region
function binDataBigSize(quizzyShopId) {
    // question & answer
    var lstBigSize = '';
    $.getJSON("/Handlers/QuizHandler.ashx", { 'command': 'bindbigsizebyquizzyshop', 'id': quizzyShopId }, function (result) {
        for (var i = 0; i < result.length; i++) {
            lstBigSize += '<div class="bigsize-item">';
            lstBigSize += bindQuestionAnswer(result[i].ListQuestion[0].Question, result[i].ListAnswer);
            lstBigSize += '</div>';
        }

        $('.bigsize').html(lstBigSize);
    });

    // big size result
    $.getJSON("/Handlers/QuizHandler.ashx", { 'command': 'bindbisizeresult', 'id': quizzyShopId }, function (result) {
        var bigSizeResult = '';
        
        for (var i = 0; i < result.length; i++) {            
            bigSizeResult += '<div class="rowElem">';
            bigSizeResult += '<label>Lời chiêm tinh</label>';
            bigSizeResult += '<div class="formRight">';
            bigSizeResult += '<textarea name="textarea" class="auto bResult" cols="" rows="4" style="width: 630px">' + result[i].Result + '</textarea>';
            bigSizeResult += '<div class="floatright"><a onclick="removeBigSizeResult(this);" title="Xóa đáp án" class="btn14 mb5 topDir"><img alt="" src="/images/icons/dark/close.png"></a></div>';
            bigSizeResult += '</div>';            
            bigSizeResult += '<div class="fix"></div>';
            bigSizeResult += '</div>';
        }

        $('.bigsize-result').html(bigSizeResult);
        $('#bigSize-result-container').show();
    });
}

function bindQuestionAnswer(question, listAnswer) {
    var html = '';
    
    html += '<div class="question">';
    
    html += '<div class="rowElem nobg">';
    html += '<label>Câu hỏi</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bQuestion" name="textarea">' + question + '</textarea>';
    html += '<div class="floatright" onclick="removeQuestion(this);">';
    html += '<a class="btn14 mb5 floatright topDir" title="Xóa câu hỏi">';
    html += '<img src="/images/icons/dark/close.png" alt=""/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<div class="answerList">';

    for (var j = 0; j < listAnswer.length; j++) {    
        html += '<div class="rowElem">';
        html += '<label>Đáp án</label>';    
        html += '<div class="formRight">';
        html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bAnswer" name="textarea">' + listAnswer[j].Answer + '</textarea>';    
        html += '<div class="floatright">';
        html += '<a class="btn14 mb5 topDir" title="Thêm đáp án" onclick="createAnswer(this);">';
        html += '<img src="/images/icons/dark/add.png" alt="" />';
        html += '</a>';
        html += '<br/>';
        html += '<a class="btn14 mb5 topDir" title="Xóa đáp án" onclick="removeAnswer(this);">';
        html += '<img src="/images/icons/dark/close.png" alt=""/>';
        html += '</a>';
        html += '</div>';
        html += '</div>';
        html += '</div>';
    }    
    
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';
    
    return html;
}
//#endregion

/***************************************
= Create Question
-------------------------------------- */
//#region
function createQuestion() {
    var html = '';

    html += '<div class="bigsize-item">';
    html += '<div class="question">';
    html += '<div class="rowElem nobg">';
    html += '<label>Câu hỏi</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bQuestion" name="textarea"></textarea>';
    html += '<div class="floatright" onclick="removeQuestion(this);">';
    html += '<a class="btn14 mb5 floatright topDir" title="Xóa câu hỏi">';
    html += '<img src="/images/icons/dark/close.png" alt=""/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '<div class="fix"></div>';
    html += '</div>';

    html += '<div class="answerList">';
    html += '<div class="rowElem">';
    html += '<label>Đáp án</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bAnswer" name="textarea"></textarea>';
    html += '<div class="floatright">';
    html += '<a class="btn14 mb5 topDir" title="Thêm đáp án" onclick="createAnswer(this);">';
    html += '<img src="/images/icons/dark/add.png" alt="" />';
    html += '</a>';
    html += '<br/>';
    html += '<a class="btn14 mb5 topDir" title="Xóa đáp án" onclick="removeAnswer(this);">';
    html += '<img src="/images/icons/dark/close.png" alt=""/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '</div>';
    html += '<div class="curves"></div>';
    html += '</div>';
    html += '</div>';

    $('.bigsize').append(html);

    delegateTooltip();
}
//#endregion
/***************************************
= Remove Question
-------------------------------------- */
//#region
function removeQuestion(obj) {
    $(obj).parents('.bigsize-item').fadeOut('slow', function () {
        $(this).remove();
    });                            
}
//#endregion

/***************************************
= Create Answer
-------------------------------------- */
//#region
function createAnswer(obj) {
    var html = '';    
    html += '<div class="rowElem">';
    html += '<label>Đáp án</label>';
    html += '<div class="formRight">';
    html += '<textarea style="width: 630px" rows="2" cols="" class="validate[required] bAnswer" name="textarea"></textarea>';
    html += '<div class="floatright">';
    html += '<a class="btn14 mb5" onclick="createAnswer(this);">';
    html += '<img src="/images/icons/dark/add.png" alt="" class="floatright topDir" title="Thêm đáp án"/>';
    html += '</a>';
    html += '<br/>';
    html += '<a class="btn14 mb5" onclick="removeAnswer(this);">';
    html += '<img src="/images/icons/dark/close.png" alt="" class="floatright topDir" title="Xóa đáp án"/>';
    html += '</a>';
    html += '</div>';
    html += '</div>';
    html += '</div>';

    $(obj).parents('.answerList').append(html);
}
//#endregion
/***************************************
= Remove Answer
-------------------------------------- */
//#region
function removeAnswer(obj) {
    $(obj).parents('.rowElem').fadeOut('slow', function () {
        $(this).remove();
    });                    
}
//#endregion

//**************************************************************************************************************************************************************//
// PREVIEW
//**************************************************************************************************************************************************************//

/***************************************
= Preview Image
-------------------------------------- */

function viewImage(objName, size) {

    var imgPath = $('#' + objName).val();
    
    if (imgPath.length > 0) {
        $('#popup_container').css('display', 'block');
        $('#popup_title').empty();
        $('#popup_message').empty();

        $('#popup_title').append(imgPath);
        
        $('#popup_message').removeAttr('style', '');

        var body = '';
        body += String.format('<center><img src="{0}/{1}" width="{2}" alt=""/></center>', SITE_URL, imgPath, size);
        console.log(body);

        $('#popup_message').append(body);
    }        
}
function closeViewImage() {
    //$('#viewImage').hide();
    $('#popup_container').hide();
}
//#endregion


/***************************************
= Base64
-------------------------------------- */
var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function (string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
}

function closePreview() {
    $('#popup_container').hide();
}
